import editForm from "../form.vue";
import { getLogList, type Log } from "@/api/system";
import { usePublicHooks } from "@/views/hooks";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, h } from "vue";

export function userLog() {
  const form = reactive<Log>({
    current: 1,
    size: 20,
    status: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const { tagStyle } = usePublicHooks();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "业务模块",
      prop: "busType",
      width: 180
    },
    {
      label: "具体业务",
      prop: "title",
      width: 180
    },
    {
      label: "耗时",
      width: 80,
      prop: "cost"
    },
    {
      label: "系统",
      prop: "os",
      width: 150
    },
    {
      label: "浏览器",
      prop: "browser",
      width: 150
    },
    {
      label: "IP",
      prop: "remoteAddr",
      width: 150
    },
    {
      label: "归属地",
      width: 100,
      prop: "ipRegion"
    },
    {
      label: "结果",
      prop: "status",
      width: 80,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.status === "成功")}>
          {row.status}
        </el-tag>
      )
    },
    {
      label: "操作人",
      width: 80,
      prop: "creatorName"
    },
    {
      label: "操作时间",
      width: 180,
      prop: "created"
    },
    {
      label: "操作",
      fixed: "right",
      width: 80,
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    form.size = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.current = val;
    onSearch();
  }

  function onSearch() {
    loading.value = true;
    getLogList(form)
      .then(data => {
        dataList.value = data.records;
        pagination.total = data.total;
        pagination.pageSize = data.size;
        pagination.currentPage = data.current;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  const resetForm = (formEl: any) => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(row?: Log) {
    addDialog({
      title: `查看日志`,
      props: {
        formInline: row
      },
      width: "70%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef })
    });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange
  };
}
